import React, { ChangeEvent, FormEvent, useState } from 'react';
import "./textarea.scss";

/**
 * @param name 原生 textarea name 属性
 * @param id 原生 textarea id 属性
 * @param cols 原生 textarea cols 属性，文本域列数量
 * @param rows 原生 textarea rows 属性，文本域行数量
 * @param disabled 是否禁用
 * @param resize 文本域拖拽方向
 * @param maxlength 最大输入字符数量
 * @param showWordCount 是否显示字符数量
 * @param defaultValue 默认值
 * @param onBlur 失去焦点触发的函数
 * @param onFocus 获取焦点触发的函数
 * @param onChange 仅当输入值改变时，当输入框失去焦点或用户按Enter时触发
 * @param onInput 输入时触发的函数
 */
interface Props {
    name?: string,
    id?: string,
    cols?: number,
    rows?: number,
    disabled?: boolean,
    resize?: 'none' | 'both' | 'horizontal' | 'vertical' | 'block' | 'inline',
    maxlength?: number,
    showWordCount?: boolean,
    defaultValue?: string,
    onBlur?: () => void,
    onFocus?: () => void,
    onChange?: (e: ChangeEvent<HTMLTextAreaElement>) => void,
    onInput?: (e: FormEvent<HTMLTextAreaElement>) => void,
}

const Textarea = ({
    name,
    id,
    cols = 30,
    rows = 3,
    disabled = false,
    resize = "none",
    maxlength,
    showWordCount = false,
    defaultValue = "",
    onBlur = () => { },
    onFocus = () => { },
    onChange = () => { },
    onInput = () => { },
}: Props) => {
    const [value, setValue] = useState<string>(defaultValue)

    const [borderColor, setBorderColor] = useState<string>("")
    return (
        <div className="pe-textarea" style={{ resize: resize, '--pe-textarea-border-color': borderColor } as React.CSSProperties}>
            <textarea className="pe-textarea-inner" name={name} id={id} cols={cols} rows={rows} maxLength={maxlength}
                onBlur={() => {
                    setBorderColor("var(--pe-color-border)")
                    onBlur()
                }}
                onFocus={() => {
                    setBorderColor("var(--pe-color-primary)")
                    onFocus()
                }}
                onChange={(e) => {
                    onChange(e)
                }}
                onInput={(e) => {
                    const value1 = (e.target as HTMLInputElement).value
                    setValue(value1)
                    onInput(e)
                }}></textarea>
            {
                showWordCount ? (
                    <span className="pe-textarea-count">{value.length}{maxlength !== undefined ?
                        `/${maxlength}` : ''}</span>
                ) : null
            }
            {
                disabled ? <div className="pe-disabled"></div> : null
            }
        </div>
    )
}

export default Textarea